﻿using FreeSql;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Domain.KeepModel.Process;
using IMES.Common.Dtos; 
using MediatR;
 
namespace Keep.API.Appliction.Command.ProcessFile
{
    /// <summary>
    /// 工序列表
    /// </summary>
    public class WorkingProcedureListHandler : IRequestHandler<WorkingProcedureListCommon, Result>
    {
         
        private readonly IFreeSql _fsql;
        /// <summary>
        /// 构造函数
        /// </summary> 
        public WorkingProcedureListHandler( IFreeSql fsql)
        { 
            _fsql = fsql;
        }
        public async Task<Result> Handle(WorkingProcedureListCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.success, Messege = "success", Data = null };
            try
            {
                // 使用FreeSql进行关联查询及选择字段
                var list = _fsql.Select<WorkingProcedure, ProcessRoute, ProcessManagement, WType>()
                   .LeftJoin((w, p, m, t) => w.ProcessRouteId == p.ProcessRouteId)
                   .LeftJoin((w, p, m, t) => w.WorkingProcedureType == m.ProcessID)
                   .LeftJoin((w, p, m, t) => w.WTypeId == t.WTypeId)
                   .WhereIf(!string.IsNullOrEmpty(request.ProcessRouteNumber),(w, p, m, t) =>  p.ProcessRouteNumber == request.ProcessRouteNumber)
                   .ToList((w, p, m, t) => new
                   {
                       WorkingProcedureId = w.WorkingProcedureId, 
                       WTypeId = w.WorkingProcedureType,
                       WTypeName = t.WTypeName,
                       WorkingProcedureType = w.WorkingProcedureType,
                       WorkingProcedureTypeName = m.ProcessName,
                       WorkingNumBer = w.WorkingNumBer,
                       ProcessRouteName = p.ProcessRouteName,
                       ProcessRouteId = p.ProcessRouteId,
                       CreateId = w.CreateId,
                       CreateName = w.CreateName,
                       CreateDate = w.CreateDate,
                       UpdateId = w.UpdateId,
                       UpdateName = w.UpdateName,
                       UpdateDate = w.UpdateDate
                   });

                result.Data = list;
            }
            catch (Exception ex)
            {
                result.Messege = ex.Message;
                result.Code = (int)CodeEnum.error;
            }
            return result;
             
        }


    }
}
